import os
import platform
import subprocess

import click
from pyfiglet import Figlet
from colorama import Fore, Style, init
from six import print_
from termcolor import colored
from .Chat import *


# 进行聊天
def AgentChat(message):
    try:
        response = request(message)
        """
        response是一个包含以下键值对的字典：
        {
            "description": "切换Test目录",
            "code": "cd Test",
            "is_code": True,
            "Native": True
        }
        """
        if not response:
            return "认证错误，请稍后再试！"
        else:
            # print(response)
            description = response["description"]
            code = response["code"]
            is_code = response["is_code"]
            Native = response["Native"]

            print(f"{Fore.BLUE}{description}{Style.RESET_ALL}")

            if is_code:
                user_input = input(f"{code}是否执行该命令？(y/n): ")
                if user_input.lower() == "y":
                    if is_code and Native:
                        execute_c = execute_command(code)
                        print(Fore.CYAN + f"{execute_c}" + Style.RESET_ALL)
                        AgentChat(f"执行结果：{execute_c}")
                    if is_code and not Native:
                        if ["clear", "Clear-Host", "cls"] in code:
                            clear_history()
                            clear_Shell()

                        execute_c = execute_command(code)
                        print(Fore.CYAN + f"{execute_c}" + Style.RESET_ALL)
                else:
                    return "取消执行命令"
    except Exception as e:
        return "Sorry, I'm having trouble connecting to the server at this time."


# 清理屏幕的函数
def clear_Shell():
    os.system('clear')
    clear_history()


# 执行命令的函数
def execute_command(command):
    # 执行命令并获取结果，支持Windows(Powershell)，Linux，MacOS
    system = platform.system().lower()

    if system == "windows":
        # 如果是 PowerShell 的 cd 命令，直接调用 os.chdir()
        if command.strip().lower().startswith("cd") or command.strip().lower().startswith("Set-Location -Path"):
            change_directory(command)
        else:
            # 其他 PowerShell 命令
            shell = ["powershell", "-Command", command]
    elif system == "linux":
        if command.strip().lower().startswith("cd"):
            change_directory(command)
        else:
            shell = ["bash", "-c", command]
    elif system == "darwin":
        if command.strip().lower().startswith("cd"):
            change_directory(command)
        else:
            shell = ["zsh", "-c", command]
    else:
        raise ValueError("Unsupported operating system")

    try:
        result = subprocess.run(shell, capture_output=True, text=True, check=True)
        return result.stdout
    except subprocess.CalledProcessError as e:
        # 输出红色颜色信息
        print(f"{Fore.RED}执行失败: {str(e)}", Fore.RESET)
        # 如果命令执行失败，返回错误信息
        AgentChat(f"执行失败,失败原因：{str(e)}")


# 切换目录函数
def change_directory(directory):
    try:
        if directory.startswith("Set-Location -Path"):
            path = directory.split()[2]
            os.chdir(path)
            return f"成功切换到目录: {path}"

        path = directory.split()[1]
        os.chdir(path)
        return f"成功切换到目录: {path}"
    except Exception as e:
        AgentChat(f"切换目录失败: {str(e)}，本地路径为：{os.getcwd()},请使用cd命令")


@click.command()
def terminal():
    init()
    f = Figlet(font=Config.terminal_font)  # font为字体，可自行选择
    print_(colored(f.renderText(Config.render_text),
                   color=Config.render_text_color)
           )  # renderText为终端输出名称，render_text_color为终端输出名称颜色
    while True:
        current_path = os.getcwd()
        user_input = input(f"{current_path}> " + Style.BRIGHT)
        if user_input.lower() in ["exit", "quit"]:
            print(Fore.BLUE + "拜拜!")
            break
        elif user_input.lower() in ["清理聊天", "--clsChat", "-clsChat", "--ch", "-ch"]:
            clear_history()
        elif user_input.lower() in ["清屏", "--cls", "-cls", "clear", "cls", "-c", "--c", "清理屏幕"]:
            clear_Shell()
            continue
        elif user_input.lower() in ["--help", "-h", "帮助", "help"]:
            print(Fore.WHITE +
                  "输入 --clsChat 或 --ch 清理聊天记录\n"
                  "输入 --cls 或 --c 清理屏幕\n"
                  "输入 exit 退出程序\n"
                  + Style.RESET_ALL)

        response = AgentChat(user_input)
        if response is not None and ("认证错误" in response or "API错误" in response):
            print(Fore.RED + response)
            break


if __name__ == '__main__':
    terminal()
